package edu.uwlax.cs.oayonlinestore.service;

import edu.uwlax.cs.oayonlinestore.entities.Order;
import edu.uwlax.cs.oayonlinestore.exceptions.AccessDeniedException;
import edu.uwlax.cs.oayonlinestore.server.Session;
import edu.uwlax.cs.oayonlinestore.stadis.OrderStatus;
import edu.uwlax.cs.oayonlinestore.vo.UserDetailsVO;

public class AccessControl {

	public static void forceBrowseOwnOrders(int userID) {
		UserDetailsVO u = getUser(false);
		if (u.isIsSalesManager())
			return;
		if (u.isIsSalesStaff())
			return;
		if (u.getId() == userID) {
			if (u.isIsNormalCustomer())
				return;
			if (u.isIsIndustrialCustomer())
				return;
		}
		throw new AccessDeniedException();
	}

	public static void forceCanAccessInventoryReports() {
		UserDetailsVO u = getUser(false);
		if (u.isCanBeCategoryPerson())
			return;
		// TODO: check for appropriate rights
		throw new AccessDeniedException();
	}

	public static void forceCanAdminOrders() {
		UserDetailsVO u = getUser(false);
		if (u.isIsSalesManager())
			return;
		if (u.isIsSalesStaff())
			return;
		throw new AccessDeniedException();
	}

	public static void forceCanAdminPrices() {
		UserDetailsVO u = getUser(false);
		if (u.isIsSalesManager())
			return;
		throw new AccessDeniedException();
	}

	public static void forceCanCreateOrder() {
		UserDetailsVO u = getUser(false);
		if (u.isIsSalesManager())
			return;
		if (u.isIsSalesStaff())
			return;
		if (u.isIsNormalCustomer())
			return;
		if (u.isIsIndustrialCustomer())
			return;
		throw new AccessDeniedException();
	}

	public static void forceCanEditOrder(Order o) {
		UserDetailsVO u = getUser(false);

		if (u.isIsSalesManager() || u.isIsSalesStaff())
			return;

		boolean ownOrder = o.getUser().getId() == u.getId();
		boolean inProgrss = o.getStatus().equals(OrderStatus.IN_PROGRESS);

		if (ownOrder && inProgrss)
			if (u.isIsNormalCustomer() || u.isIsIndustrialCustomer())
				return;

		throw new AccessDeniedException();
	}

	public static void forceCanEditRetExForms() {
		UserDetailsVO u = getUser(false);
		if (u.isIsSalesManager())
			return;
		if (u.isIsSalesStaff())
			return;
		throw new AccessDeniedException();
	}

	public static void forceCanReadOrder(Order o) {
		UserDetailsVO u = getUser(false);

		if (u.isIsSalesManager() || u.isIsSalesStaff())
			return;

		if (o.getUser().getId() == u.getId())
			if (u.isIsNormalCustomer() || u.isIsIndustrialCustomer())
				return;

		throw new AccessDeniedException();
	}

	public static void forceCanViewSalesReport() {
		UserDetailsVO u = getUser(false);
		if (u.isIsSalesManager())
			return;
		throw new AccessDeniedException();
	}

	private static UserDetailsVO getUser(boolean allowAnonymous) {
		UserDetailsVO u = Session.get().getUser();
		if (!allowAnonymous && (u.getId() == 0))
			throw new AccessDeniedException();
		return u;
	}

}
